import threading
import PySimpleGUI as sg
from ui import main_layout, serach, win_icon, Lpso_info_window, \
    pan_name_mapping, Qfso_info_window, _login_window, serach
from lpso.lp_parse import lp_tables_list
from qfso.qf_parse import qf_tables_list, QianFanSo
from settings import load_settings, SETTINGS_FILE, save_settings
import pyperclip


class UI():
    def __init__(self):
        self.top_window = sg.Window('网盘搜索神器v1.0', main_layout, finalize=True,
                                    grab_anywhere=False, alpha_channel=1, icon=win_icon)
        self.datas = [[]]
        self.pan_name = ''
        self.cookie = load_settings(SETTINGS_FILE)
        print(self.cookie)

    def run_task(self, pan_name):
        if self.pan_name == 'Lpso':
            self.datas = lp_tables_list(self.values.get('-input-'))
        elif self.pan_name == 'Qfso':
            self.datas = qf_tables_list(self.values.get('-input-'), self.cookie.get('QfsCookie'))
        self.top_window.write_event_value('-THREAD-', '*** The thread says.... "I am finished" ***')

    def circle_event(self):
        search_layout_active = False
        login_layout_active = False
        # 由于搜索时间过长，体验较差，因此通过多线程加入加载转圈动画
        # 线程标志位, 用来控制搜索io图片的加载
        thread = None
        search_window: sg.Window
        login_window: sg.Window

        while True:
            # 循环读取窗口信息，事件和值
            self.event, self.values = self.top_window.read(timeout=100)

            # 如果触发关闭事件就关闭窗口
            if self.event in (sg.WIN_CLOSED, 'Exit'):
                break

            if self.event == "serach" and not search_layout_active:
                self.pan_name = pan_name_mapping.get(self.values.get('pan_name'))
                if self.values.get('-input-'):
                    # 没有cookie信息或者cookie信息已经过期
                    if self.pan_name == 'Qfso' and not self.cookie.get('QfsCookie'):
                        sg.popup_auto_close('未检测到有效的cookie，为你生成登录窗口', keep_on_top=True, icon=serach)
                        login_window = _login_window()
                        login_layout_active = True

                    else:
                        thread = threading.Thread(target=self.run_task,
                                                  args=(self.pan_name,), daemon=True)
                        thread.start()
                else:
                    sg.popup_error("请输入关键字再点击搜索！！！", icon=serach)

            if self.event == '-THREAD-':
                # 结束线程
                thread.join(timeout=0)
                # 结束加载条
                sg.popup_animated(None)
                # 清除标志位
                thread, timeout = None, None
                if self.pan_name == 'Lpso':
                    search_window = Lpso_info_window(self.datas)
                elif self.pan_name == 'Qfso':
                    search_window = Qfso_info_window(self.datas)
                search_layout_active = True

            # 播放加载动画
            if thread is not None:
                sg.popup_animated(sg.DEFAULT_BASE64_LOADING_GIF, background_color='white', transparent_color='white',
                                  time_between_frames=10, message='正在搜索网盘资源....', text_color="blue", font="1px", icon=serach)

            # 生成搜索资源画面，加载资源搜索窗口
            if search_layout_active:
                search_event, search_value = search_window.read(timeout=1000)
                if search_event in (sg.WIN_CLOSED, 'Exit'):
                    search_layout_active = False
                    search_window.close()
                elif search_event == '_table_':
                    # 获得表格点击行的位置
                    url = search_window['_table_'].get()[int(search_value['_table_'][0])][-1]
                    pyperclip.copy(url)
                    sg.popup_quick_message('url已经复制到剪切板, 请在浏览器打开', text_color='#2ecc71', font='3px', keep_on_top=True)

            if login_layout_active:
                login_event, login_value = login_window.read(timeout=1000)
                if login_event in (sg.WIN_CLOSED, 'Exit'):
                    login_layout_active = False
                    login_window.close()
                elif login_event == '-login-':
                    qf = QianFanSo()
                    qf.get_csrf()
                    qf.get_captcha()
                    account = login_value.get('-account-')
                    password = login_value.get('-password-')
                    QfCookie = qf.login_cookie(account=account, password=password)
                    if QfCookie:
                        self.cookie.update(QfsCookie=QfCookie)
                        save_settings(SETTINGS_FILE, self.cookie)
                        sg.popup_ok('登录成功！！', keep_on_top=True, icon=serach)
                        login_layout_active = False
                        login_window.close()
                    else:
                        sg.popup_error('登陆失败请重试！！', keep_on_top=True, icon=serach)

        self.top_window.close()


if __name__ == '__main__':
    ui = UI()
    ui.circle_event()
